package com.xiaojiezhu.netty.base.protocol;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * 作者 zxj<br>
 * 时间 2017/7/14 17:03
 * 说明 ...
 */
public class ServerHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("active");

    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        CobraProtocol cobraProtocol = (CobraProtocol) msg;
        System.out.println("服务端:接收到的消息:" + cobraProtocol + "," + new String(cobraProtocol.getContent()));

        // 回写数据给客户端
        String str = "Hi I am Server ...";
        CobraProtocol response = new CobraProtocol("JSON_STRING",str.getBytes("UTF-8"));
        // 当服务端完成写操作后，关闭与客户端的连接
        ctx.writeAndFlush(response);
        // .addListener(ChannelFutureListener.CLOSE);

        // 当有写操作时，不需要手动释放msg的引用
        // 当只有读操作时，才需要手动释放msg的引用
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
